﻿using System;
using System.IO.Ports;
using System.Linq;
using System.Windows.Forms;
using oModbus;
using oModbus.Device;
using oModbus.Message;
using oModbus.Utility;

namespace Sample
{
    public partial class SlaveForm : Form
    {
        public SlaveForm()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBoxSerialPorts.Items.Clear();
            foreach (var port in SerialPort.GetPortNames())
            {
                comboBoxSerialPorts.Items.Add(port);
            }
            if (comboBoxSerialPorts.Items.Count > 0)
                comboBoxSerialPorts.SelectedIndex = 0;
            comboBoxParity.Items.Clear();
            comboBoxParity.Items.Add(Parity.None.ToString());
            comboBoxParity.Items.Add(Parity.Odd.ToString());
            comboBoxParity.Items.Add(Parity.Even.ToString());
            comboBoxParity.Items.Add(Parity.Mark.ToString());
            comboBoxParity.Items.Add(Parity.Space.ToString());
            comboBoxParity.SelectedIndex = 0;
            comboBoxDataBits.SelectedIndex = 0;
            comboBoxStopBits.SelectedIndex = 0;
            BtnConnect.Enabled = true;
            BtnDisconnect.Enabled = false;
            comboBoxBaudRate.SelectedIndex = 1;
        }
        //  private ITransmission _transmission;
        private void BtnConnect_Click(object sender, EventArgs e)
        {
            SerialPort port = new SerialPort(comboBoxSerialPorts.Text)
            {
                BaudRate = Convert.ToInt32(comboBoxBaudRate.Text),
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One
            };
            switch (comboBoxStopBits.Text)
            {
                case "None":
                    port.StopBits = StopBits.None;
                    break;
                case "1":
                    port.StopBits = StopBits.One;
                    break;
                case "1.5":
                    port.StopBits = StopBits.OnePointFive;
                    break;
                case "2":
                    port.StopBits = StopBits.Two;
                    break;

            }
            var temp = new SerialTransmission(port);
            if (temp.Open())
            {
                _slave = new ModbusSlave(1, temp);
                _slave.ReceivedMessageEvent += _transmission_ReceivedMessageEvent;
                _slave.ReceivedMessageEvent += _transmission_ReceivedMessageEvent;
                _slave.ReadCoilEvent += _slave_ReadCoilEvent;
                BtnConnect.Enabled = false;
                BtnDisconnect.Enabled = true;
            }
            else
            {
                MessageBox.Show(@"打开失败");
            }
 
        }

        private void _slave_ReadCoilEvent(ReadCoilRequest obj)
        {
            ReadCoilResponse response = new ReadCoilResponse(_slave.SlaveId, new byte[] { 0x01, 02 }.ToList());
            _slave.Send(response);
        }

        private ModbusSlave _slave;
        private void _transmission_ReceivedMessageEvent(byte[] data)
        {
            Show(data);
        }

        private void Show(byte[] data)
        {
            if (txtInfo.InvokeRequired)
            {
                //后端线程向主线程记日志
                Invoke(new Action<byte[]>(Show), data);
            }
            else
            {
                //主线程直接记日志
                if (ckbHex.Checked)
                {
                    txtInfo.Text += data.GetHexString() + Environment.NewLine;
                }
                else
                {
                    txtInfo.Text += data.GetHexString() + Environment.NewLine;
                }
            }
        }

        private void BtnDisconnect_Click(object sender, EventArgs e)
        {
            //_transmission.Close();
            //_transmission.ReceivedMessageEvent -= _transmission_ReceivedMessageEvent;

            _slave.Close();
            _slave.ReceivedMessageEvent -= _transmission_ReceivedMessageEvent;

            BtnConnect.Enabled = true;
            BtnDisconnect.Enabled = false;
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            //ushort startAddress = 100;
            //ushort number = 5;

            // ReadCoilRequest request = new ReadCoilRequest(1, startAddress, number);
            //byte[] data = request.PackingMessage();
            // ReadCoilRequest res = new ReadCoilRequest(data);

            // _slave.Send(request);
            //ReadDiscreteInputRequest s = new ReadDiscreteInputRequest(1, 00, 01);

            //byte[] d = s.PackingMessage();
            //Show(d);

            //byte[] daBytes = new byte[] { 0xff };
            //ReadDiscreteInputResponse response = new ReadDiscreteInputResponse(01, daBytes.ToList());

            //response.InputState = daBytes.ToList();
            //byte[] d = response.PackingMessage();
            //Show(d);
            //ReadDiscreteInputResponse response2 = new ReadDiscreteInputResponse(d);

            //byte[] sdsdfs = response2.PackingMessage();
            //string sss = "";
            //_transmission.Send("ssss".GetBytes());

            //var s = new ReadInputRegisterRequest(2, 0, 01);
            //byte[] d = s.PackingMessage();
            //Show(d);

            ushort state = 123;
            byte[] inputState = state.GetBytes();

            //     MessageData.AddRange();//开始地址
            var s = new ReadInputRegisterResponse(2, inputState.ToList());
            byte[] d = s.PackingMessage();
            Show(d);

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInfo.Text = "";
        }
    }
}
